package com.etone.ibatistest.dao;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;

import com.etone.ibatistest.entity.User;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class UserDaoImpl implements UserDao {

	private static SqlMapClient sqlMapClient = null;
	
	static{
		try {
			Reader reader = Resources.getResourceAsReader("com/etone/ibatistest/map/SqlMapConfig.xml");
			sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
			reader.close();
		} catch (IOException e) {
		}
	}
	
	@Override
	public void addUser(User user) {

		try {
			sqlMapClient.insert("insertUser", user);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void addUserBySequence(User user) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean delUserById(int id) {
		int r = 0;
		try {
			r = sqlMapClient.delete("delUserById",id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(r>0) return true;
		else return false;
	}

	@Override
	public void updateUser(User user) {

		try {
			sqlMapClient.update("updateUser", user);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public List<User> queryAllUser() {

		List<User> list = null;
		try {
			list = sqlMapClient.queryForList("selectAllUser");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return list;
	}

	@Override
	public List<User> queryUserByName(String name) {
		List<User> list = null;
		try {
			list = sqlMapClient.queryForList("selectByName", name);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public User queryUserById(int id) {
		User user = null;
		try {
			user = (User) sqlMapClient.queryForObject("selectUserById",id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}
	
	

}
